﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using DaInterFace;
using DaInterFace.XMode;

namespace DaFunction.XMode
{
    public class XModeAPI : IXModeApi
    {
        private static Dictionary<String, IXClass> _classInstanceList = new Dictionary<String, IXClass>();
        public static IXMode DaXMode;

        public String Code(String parameters, String path, String config)
        {
            XCodeResult xcr = new XCodeResult();

            String[] splitCode = path.Split('.');
            ConfigStruct cfg = new ConfigStruct(config);
            if (!cfg.Right)
            {
                xcr.Result = EnumResult.Error;
                xcr.Message = "配置信息错误";
            }
            else if (splitCode.Length != 2)
            {
                xcr.Result = EnumResult.Error;
                xcr.Message = "错误的功能代码！";
            }
            else
            {
                DateTime curtime = DateTime.Now;
                String file = splitCode[0];
                String meth = splitCode[1];
                IXClass classInstance = null;
                if (_classInstanceList.ContainsKey(file))
                {
                    classInstance = _classInstanceList[file];
                }
                else
                {
                    try
                    {
                        Assembly ass = Assembly.Load(file);  //加载dll文件
                        Type tp = ass.GetType(file + "." + file);  //获取类名，必须 命名空间+类名
                        classInstance = (IXClass)Activator.CreateInstance(tp, new Object[] { DaXMode });  //建立实例
                        _classInstanceList.Add(file, classInstance);
                    }
                    catch (Exception ex)
                    {
                        xcr.Result = EnumResult.Error;
                        xcr.Message = "错误的功能代码！";
                    }
                }
                if (classInstance != null)
                {
                    classInstance.Code(meth, xcr);
                }

                DaXMode.Message(MessageType.Note, path + ":" + xcr.Message, (DateTime.Now - curtime).TotalMilliseconds);
            }

            return DaXMode.Serializer.Serialize(typeof(XCodeResult), xcr, xcr.SerialType);
        }
    }

    [ServiceContract()]
    public interface IXModeApi
    {
        [OperationContract]
        string Code(String parameters, String path, String config);
    }
}
